package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计数据
 *
 * @author admin
 * @date 2024/9/21
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计营业额
     */
    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        String dateStr = StringUtils.join(dateList, ",");
        //     添加营业额集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //     设置查询条件
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(dateStr)
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

        return turnoverReportVO;
    }

    private static List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        //     添加日期集合
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 统计用户数量
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 获取日期列表
        List<LocalDate> dateList = getDateList(begin, end);
        //     获取新增用户数量
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", endTime);
            // 统计用户总量
            Integer totalUser = userMapper.getByMap(map);

            // 统计新增用户
            map.put("begin", beginTime);
            Integer newUser = userMapper.getByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 统计订单数量
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 查询所有订单数量
            Integer orderCount = orderMapper.getByStatusMap(map);

            //     查询有效订单数量
            map.put("status", Orders.COMPLETED);
            Integer validCount = orderMapper.getByStatusMap(map);

            orderCountList.add(orderCount);
            validOrderCountList.add(validCount);
        }

        //     计算订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //     计算有效订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //     计算有效订单率
        Double orderCompletionRate = totalOrderCount != 0 ? validOrderCount.doubleValue() / totalOrderCount : 0;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名10
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            //     查询销量排名top10
            List<GoodsSalesDTO> goodsList = orderMapper.getSalesTop10(map);
            List<String> names = goodsList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
            List<Integer> numbers = goodsList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

            return SalesTop10ReportVO.builder()
                    .nameList(StringUtils.join(names, ","))
                    .numberList(StringUtils.join(numbers, ","))
                    .build();
    }

    /**
     * 导出excel
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
    //     获取最近30日数据
        LocalDate date = LocalDate.now();
        LocalDate beginDate = date.minusDays(30);
        LocalDate endDate = date.minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
    //     获取营业额数据
        BusinessDataVO businessDataVO = workspaceService.businessData(beginTime, endTime);
    //     写入excel
        InputStream path = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(path);
            // 填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");
        //     填充日期
            sheet.getRow(1).getCell(1).setCellValue("日期：" + beginDate + "至" + endDate);
        //     填充营业额数据
            XSSFRow row3 = sheet.getRow(3);
            row3.getCell(2).setCellValue(businessDataVO.getTurnover());
            row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row3.getCell(6).setCellValue(businessDataVO.getNewUsers());

            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());
        // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate d1 = beginDate.plusDays(i);
                XSSFRow row = sheet.getRow(7 + i);
                BusinessDataVO dataVO = workspaceService.businessData(LocalDateTime.of(d1, LocalTime.MIN), LocalDateTime.of(d1, LocalTime.MAX));
                row.getCell(1).setCellValue(String.valueOf(d1));
                row.getCell(2).setCellValue(dataVO.getTurnover());
                row.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(dataVO.getUnitPrice());
                row.getCell(6).setCellValue(dataVO.getNewUsers());
            }

        //     将excel下载到客户端
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
        //     关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
